const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

var http = {
  get: function (url, data, callback) {
    var url = 'http://tieba_with_think.cc' + url;

    var sid = wx.getStorageSync("cookie");
    if (sid) {
      data.sid = sid;
    }
    wx.request({
      url: url, //仅为示例，并非真实的接口地址
      data: data,
      success: function (resp) {
        if (resp) {
          if (resp.data.sid != data.sid) {
            console.log("服务器传递过来 ", resp);
            data.sid = resp.data.sid;
            wx.setStorageSync("cookie", resp.data.sid);
            getApp().globalData.userobj = resp.data.user;
          }
          callback(resp);
        }
      }

    })
  },

  post: function (url, data, callback) {
    var url = 'http://tieba_with_think.cc' + url;
    var sid = wx.getStorageSync("cookie");
    if (sid) {
      data.sid = sid;
    }
    wx.request({
      url: url,
      data: data,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      success: function (resp) {
        if (resp.data.sid != data.sid) {
          data.sid = resp.data.sid;
          wx.setStorageSync("cookie", resp.data.sid);
          getApp().globalData.userobj = resp.data.user;
        }
        callback(resp);
      }
    })
  }
}

var scrollHead = function (e, that) {
  var pos = "topPosition.changePosition";
  var zindex = "topPosition.zIndex";
  if (e.scrollTop > 10) {
    that.flag = true;
    that.setData({
      [pos]: 'fixed',
      [zindex]: 998
    });
  } else {
    that.setData({
      [pos]: "absolute",
      [zindex]: 1
    });
  }
}

var modal = {
  show: function (obj, trans, that) {
    var animation = wx.createAnimation(obj);
    animation.bottom(trans).step();
    that.setData({
      animationData: animation.export()
    });
  },

  hide: function (obj, trans, that) {
    var animation = wx.createAnimation(obj);
    animation.bottom(trans).step();
    that.setData({
      animationData: animation.export()
    });
  }

}


var picture = {
  takePic: function (count, callback) {
    wx.chooseImage({
      count: count,
      success: function (resp) {
        callback(resp);
      },
    })
  }
}

module.exports = {
  formatTime: formatTime,
  http: http,
  scrollHead: scrollHead,
  modal: modal,
  picture: picture
}